<template>
    <div class="full-height bg-white page-content content relative-position ">
      <yz-condition-filter
        v-model="queryParams"
        @resetSearch="resetSearch"
        @onSubmit="onSubmit"
        class="padding-t-20"
      >
        <yz-input
          v-model.trim="queryParams.dateRange"
          class="q-mr-md"
          inputType="date"
          hint="选择时间范围"
          isTip
          title="日期"
        ></yz-input>
        <workshop-search v-model="queryParams" ref="workShopSearch" :is-shift="false" @endDevice="endDevice"/>
      </yz-condition-filter>
      <div style="" class="flex justify-between items-center form-inline">
       <q-btn class="btn margin-r-10 font-size-16"
              outline
              color="primary"
              :disable="!tableData.length"
              label="导出Excel"
              @click="exportExcel"/>
        <div>
          <span style="margin-right: 6px;cursor: pointer" @click="dialogVisible=true">
                  <q-icon name="iconfont icontubiao-72" class="font-18 text-grey"/>
                  <q-tooltip max-width="300px">
                    {{ dateType === 'date' ? '时间开动率=所选设备每日班制内实际加工状态总时长/所选设备计划加工总时长x100%': '时间开动率=所选设备选择的时间段内实际加工状态总时长/所选设备选择的时间段计划加工总时长x100%'}}
                  </q-tooltip>
                </span>
          <q-toggle v-model="showScale"
                    label="启用缩放"
                    left-label
                    class="toggle-space"
                    @input="changeScale"
          />
        </div>
     </div>
       <!--    图表的标题-->
      <div class="text-center margin-l-20" style="position: relative">
       <span class="font-size-16" style="position: absolute;left: 0px; margin-bottom: 40px">共计{{deciveCount}}台机床</span>
       <span class="font-size-16">总时间开动率：{{ actuateRate || '--' }}</span>
     </div>
      <div style="height: calc(100% - 96px)" class="scroll scrollbar margin-b-20">
       <!--    图表-->
       <div ref="utilizationRate"  style="width: 100%; height: 400px;margin-top: 10px" class="padding-l-20 padding-r-20"></div>
       <!-- 表格 -->
       <div>
         <q-table
           :data="tableData"
           :columns="tableColumns"
           row-key="number"
           id="table"
           class="myTable scroll stick-last-col stick-first-col inherit stick-last-row"
           :pagination.sync="pagination"
           style="max-height: 300px"
           :hide-bottom="!!tableData.length"
         />
       </div>
     </div>
      <drawer
        title="说明"
        :visible.sync="dialogVisible"
        width="500px"
        close-on-click-modal>
        <div>
          <div>1.按照日期查询：查询当列数据所选设备每日班制内实际加工状态总时长/所选设备计划加工总时长x100%；</div>
          <div>2.总时间开动率为时间开动率的平均值</div>
        </div>
      </drawer>
    </div>
</template>
<script>
// import CustomizedSwitch from 'src/components/customized-switch'
import moment from 'moment'
import { mapGetters } from 'vuex'
import echarts from 'echarts'
import _ from 'lodash'
import { getAvailabilityList } from 'src/boot/statistics/availability-stat'
import { addListener } from 'resize-detector'
import exportStat from './components/stat-export'
import exportExcel from './components/exportAvailabilityExcel'
import Drawer from 'src/components/drawer/drawer'
moment.locale('zh-cn')

export default {
  name: 'availability-stat',
  components: {
    // CustomizedSwitch,
    Drawer
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    deciveCount () {
      return this.cloneParams.devices[0] === 'all' ? this.deviceOptions.length : this.deviceIds.length
    }
  },
  data () {
    return {
      dialogVisible: false,
      deviceIds: [], // 所选设备Id列表
      deviceOptions: [], // 所选设备Id列表
      showScale: false, // 是否可以缩放
      utilizationChart: null, // 开动率图表
      // timeRange: [moment(new Date()).add(1, 'hours').subtract(8, 'hours').toDate(), moment(new Date()).add(1, 'hours').toDate()],
      timeRange: [null, null],
      queryParams: {
        dateRange: [moment(new Date()).subtract(7, 'days').toDate(), new Date()],
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        workshopId: '',
        devices: ['all']
      },
      dateType: 'date',
      dateTypeOption: [
        {
          value: 'time',
          label: ' 时间 '
        },
        {
          value: 'date',
          label: ' 日期 '
        }
      ],
      pagination: {
        rowsPerPage: 0
      },
      workShopName: '',
      // 当日机床开动率
      actuateRate: 0,
      utilizationData: {
        time: [],
        value: []
      }, // 开动率源数据
      xAxisList: [],
      dataList: [],
      // 机床总数
      total: 0,
      endHour: '',
      startHour: '',
      endDate: '',
      startDate: '',
      // 表格头部数据
      tableColumns: [],
      // 表格内容
      tableData: [],
      cloneParams: {
        devices: ['all']
      },
      type: 1
    }
  },
  mounted () {
    this.getListInit()
    this.utilizationRateChart()
    this.utilizationChart._model.option.dataZoom[0].disabled = true
    addListener(this.$refs.utilizationRate, this.$utils.debounce(() => {
      if (this.utilizationChart) {
        this.utilizationChart.resize()
      }
    }, 100))
  },

  methods: {
    endDevice (val) {
      this.deviceOptions = val
    },
    getListInit () {
      this.$refs.workShopSearch.getWorkshops().then(() => {
        this.getList()
      })
    },
    // 图表缩放
    changeScale () {
      let option = _.cloneDeep(this.utilizationChart.getOption())
      option.dataZoom[0].disabled = !this.showScale
      this.utilizationChart.clear()
      this.utilizationChart.setOption(option)
    },
    // 修改所选区间
    changeSelRange () {
      if (!this.timeRange[0] && !this.timeRange[1] && this.dateType === 'time') {
        this.timeRange = [moment(new Date()).subtract(6, 'hours').toDate(), moment(new Date()).add(1, 'hour').toDate()]
      }
    },
    // 绘制开动率Echarts
    utilizationRateChart (xAxisList, availabilityData, notStartingData) {
      this.utilizationChart = echarts.init(this.$refs.utilizationRate)
      // 绘制图表
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            let htmlStr = '<div>'
            params.forEach(i => {
              htmlStr += '<div>'
              const value = !i.value && i.value !== 0 ? '--' : `${(i.value).toFixed(2)}%`
              const color = i.color
              let name = ''
              switch (i.seriesName) {
                case '时间开动率(A)':
                  name = '时间开动率'
                  break
                case '未开机占比':
                  name = '未开机占比'
                  break
              }
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;font-size:14px;border-radius:5px;background-color:' + color + ';"></span>'
              htmlStr += `${name}：${value}`
              htmlStr += '</div>'
            })

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0
          }
        ],
        grid: {
          left: 60,
          right: 20,
          top: 70,
          bottom: 50
        },
        legend: {
          data: ['时间开动率(A)'],
          right: 0,
          top: 20
        },
        xAxis: [{
          type: 'category',
          data: xAxisList,
          axisLine: {
            lineStyle: {
              color: '#d3d3d3'
            }
          },
          axisLabel: {
            color: '#333',
            margin: 20
          },
          axisTick: {
            show: false
          }
        }],
        yAxis: [{
          type: 'value',
          name: '百分比',
          nameTextStyle: {
            color: '#333',
            align: 'right',
            fontSize: 14
          },
          nameGap: 40,
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLabel: {
            formatter: function (val) {
              return val + '%'
            },
            fontSize: 12
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          splitArea: {
            show: false
          }
        }],
        series: [{
          name: '时间开动率(A)',
          type: 'line',
          data: availabilityData,
          lineStyle: {
            normal: {
              width: 3,
              color: '#5F77FD',
              shadowColor: 'rgba(95, 119, 253, 0.3)',
              shadowBlur: 8,
              shadowOffsetY: 20
            }
          },
          symbolSize: 10,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          dataZoom: [{
            type: 'inside'
          }],
          smooth: true
        }]
      }
      this.utilizationChart.setOption(option)
    },
    // 获取数据
    getList () {
      this.deviceIds = this.queryParams.devices.filter(v => v !== 'all')
      const { location } = this.queryParams
      if (this.deviceIds.length || this.queryParams.workshopId) {
        if (this.dateType === 'date') {
          this.startDate = moment(this.queryParams.dateRange[0]).format('YYYY-MM-DD')
          this.endDate = moment(this.queryParams.dateRange[1]).format('YYYY-MM-DD')
          this.type = 1
        } else {
          this.startHour = moment(this.timeRange[0]).format('YYYYMMDDHH')
          this.endHour = moment(this.timeRange[1]).format('YYYYMMDDHH')
          this.type = 4
        }
        let params = {
          startDate: this.startDate,
          endDate: this.endDate,
          startHour: this.startHour,
          endHour: this.endHour,
          type: this.type
        }
        params.deviceTreeReqVO = {
          deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
          level: location.level || null,
          schemeId: location.id || null
        }
        this.cloneParams = _.cloneDeep(this.queryParams)
        getAvailabilityList(params).then(res => {
          this.workShopName = res.data.plantNameAndWorkShopNames

          // this.total = res.data.length - 1
          let xAxisList = []
          let availabilityData = []
          let notStartingData = []
          let tableData = []
          let total = {
            deviceName: '时间开动率',
            average: this.actuateRate
          }
          if (res.data.oeeAPCReportsResVOS && res.data.oeeAPCReportsResVOS.length) {
            this.actuateRate = exportStat.getPercentage(_.sumBy(res.data.oeeAPCReportsResVOS, 'timeRate') / res.data.oeeAPCReportsResVOS.length) + '%'
            res.data.oeeAPCReportsResVOS.forEach((item) => {
              if (this.dateType === 'date') {
                xAxisList.push(moment(item.date).format('MM-DD'))
                const key = moment(item.date).format('YYYYMMDD')
                total[key] = exportStat.getPercentage(item.timeRate) + '%'
              } else {
                xAxisList.push(`${(item.hour + '').substring((item.hour + '').length - 2)}:00`)
                total[item.hour] = exportStat.getPercentage(item.timeRate) + '%'
              }
              availabilityData.push((item.timeRate) * 100)
              notStartingData.push((item.notStarting) * 100)
            })
            this.getTableColumns(res.data.oeeAPCReportsResVOS)
          } else {
            this.actuateRate = '0.00%'
          }
          if (res.data.devices && res.data.devices.length) {
            res.data.devices.forEach((item) => {
              let devicesItem = {
                deviceName: item.deviceName,
                location: item.location || '--',
                average: exportStat.getPercentage(item.total) + '%'
              }
              item.oeeAPCListDetail.forEach(i => {
                if (this.dateType === 'date') {
                  const key = moment(i.date).format('YYYYMMDD')
                  devicesItem[key] = exportStat.getPercentage(i.timeRate) + '%'
                } else {
                  devicesItem[i.hour] = exportStat.getPercentage(i.timeRate) + '%'
                }
              })
              tableData.push(devicesItem)
            })

            tableData.push(total)
            this.tableData = tableData
          } else {
            this.tableData = []
          }
          this.utilizationRateChart(xAxisList, availabilityData, notStartingData)
        })
      } else {
        this.$message.warning('所选设备数量为0，请重新选择')
      }
    },
    // 导出excel
    exportExcel () {
      const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语祯物联'
      let dataRange = ''
      let excelName = ''
      const sheetName = '机台报表_时间开动率'
      if (this.dateType === 'date') {
        // 日期
        dataRange += '日期：'
        dataRange += moment(this.cloneParams.dateRange[0]).format('YYYY-MM-DD')
        dataRange += ' 至 '
        dataRange += moment(this.cloneParams.dateRange[1]).format('YYYY-MM-DD')
        // 表名
        excelName += moment(this.cloneParams.dateRange[0]).format('YYYYMMDD')
        excelName += '-'
        excelName += moment(this.cloneParams.dateRange[1]).format('YYYYMMDD')
      } else {
        // 日期
        dataRange += '时间：'
        dataRange += moment(this.timeRange[0]).format('YYYY-MM-DD HH:mm')
        dataRange += ' 至 '
        dataRange += moment(this.timeRange[1]).format('YYYY-MM-DD HH:mm')
        // 表名
        excelName += moment(this.timeRange[0]).format('YYYYMMDDHH')
        excelName += '-'
        excelName += moment(this.timeRange[1]).format('YYYYMMDDHH')
      }
      excelName += sheetName
      const workshop = this.workShopName
      const newTableColumns = _.cloneDeep(this.tableColumns)
      newTableColumns.splice(1, 0, { name: 'location', field: 'location', label: '所在位置', align: 'left' })
      const headList = _.map(newTableColumns, 'label')
      exportExcel.availabilityExcel(companyName, dataRange, workshop, sheetName, excelName, headList, this.tableData)
    },
    // 获取表头、合计行数据
    getTableColumns (data) {
      // 拼接表头
      const tableColumns = [{ name: 'deviceName', field: 'deviceName', label: '设备名称（编号）', align: 'left' }]
      data.forEach(item => {
        let col = null
        if (this.dateType === 'date') {
          let key = moment(item.date)
          col = {
            name: key.format('YYYYMMDD'),
            field: key.format('YYYYMMDD'),
            label: `${key.format('MM-DD')}（${key.format('dddd')}）`,
            align: 'left'
          }
          item.date = key.format('YYYYMMDD')
        } else {
          let key = moment(item.hour)
          col = {
            name: item.hour,
            field: item.hour,
            label: `${(key + '').substring((key + '').length - 2)}:00`,
            align: 'left'
          }
        }
        tableColumns.push(col)
      })
      tableColumns.push({ name: 'average', field: 'average', label: '平均值', align: 'left' })

      this.tableColumns = tableColumns
    },
    // 重置
    resetSearch () {
      this.dateType = 'date'
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.$refs.workShopSearch.initData()
    },
    // 查询
    onSubmit () {
      this.getList()
    }
  }
}
</script>

<style lang="stylus" scoped>
  >>>.stick-first-col thead tr th:first-child{
    z-index 999
  }
  >>>.q-table__card .q-table__middle{
    max-height inherit !important
  }
  .stick-last-row{
    >>>.q-table{
      tbody tr{
        box-shadow 0.5px -3px 3px rgba(0,0,0,0.1)
        &:last-child {
          position sticky
          bottom 0
          z-index 3
          td {
            position sticky
            bottom 0
            z-index 3

            &:first-child{
              bottom 0
              left 0
              z-index 4
              box-shadow 3px 1px 3px rgba(0,0,0,0.1)
            }
          }
        }
      }
    }
  }
</style>
